#include <util/delay.h>
#include <avr/io.h>
//-------------------------------------------------------------
#define MOUSE_PORT   PORTD
#define MOUSE_PIN    PIND
#define MOUSE_DDR    DDRD

#define MOUSE_PD   (1<<1)
#define MOUSE_SCLK (1<<3)
#define MOUSE_SDIO (1<<5)

/*
#define MOUSE_SCLK_HI() MOUSE_DDR &= ~MOUSE_SCLK;
#define MOUSE_SCLK_LO() MOUSE_DDR |=  MOUSE_SCLK;

#define MOUSE_SDIO_HI() MOUSE_DDR &= ~MOUSE_SDIO;
#define MOUSE_SDIO_LO() MOUSE_DDR |=  MOUSE_SDIO;
*/

#define MOUSE_SCLK_HI() MOUSE_PORT |=  MOUSE_SCLK;
#define MOUSE_SCLK_LO() MOUSE_PORT &= ~MOUSE_SCLK;

#define MOUSE_SDIO_HI() MOUSE_PORT |=  MOUSE_SDIO;
#define MOUSE_SDIO_LO() MOUSE_PORT &= ~MOUSE_SDIO;


void MouseSync() 
{
	MOUSE_DDR |= MOUSE_SDIO | MOUSE_SCLK;

	MOUSE_SCLK_HI();
	MOUSE_SDIO_HI();
	_delay_us(10);

	MOUSE_PORT |= MOUSE_PD;

	_delay_us(10);

	MOUSE_PORT &= ~MOUSE_PD;

	_delay_us(10);
}

void MouseWriteByte(char data)
{
	MOUSE_DDR |= MOUSE_SDIO;

	for( char i=0;i<8;i++)
	{
		MOUSE_SCLK_LO();

		if ( ( data & 128 ) >0 )
		{
			MOUSE_SDIO_HI();
		}
		else
		{
			MOUSE_SDIO_LO();
		}

		_delay_us(10);		


		MOUSE_SCLK_HI();
		_delay_us(10);
		

		data <<=1;
	}
	
	MOUSE_DDR &= ~MOUSE_SDIO; //SDIO as input
	MOUSE_SDIO_LO();
}

char MouseReadByte()
{
	MOUSE_DDR &= ~MOUSE_SDIO; //SDIO as input
	MOUSE_SDIO_LO();

	char data = 0;

	for( char i=0;i<8;i++)
	{
		MOUSE_SCLK_LO();
		_delay_us(10);
		
		data <<=1;

		MOUSE_SCLK_HI();
		_delay_us(10);

		if ( ( MOUSE_PIN & MOUSE_SDIO ) >0 )
		{
			data |=1;
		}

	}

	return data;
}

